<template>
  <div style="width:60%;margin-top:200px;">
    <div style="text-align:center;">
      <h1>测试 Vue 认证登录 </h1>
    </div>
    <el-form :label-position="left" style="" ref="loginForm" label-width="120px" :model="loginForm">
      <!--prop:表示属性设置为校验的字段名-->
      <el-form-item label="名称" prop="account" :rules="[{required:true, message: '请输入登录邮箱', trigger: 'blur'},{type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}]">
        <el-input v-model.trim="loginForm.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="[{required: true, message: '请输入登录密码', trigger: 'blur'}]">
        <el-input type="password" v-model.trim="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
        <el-button @click="resetForm('loginForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import * as types from '@/store/types.js'
import api from '@/store/api.js'
export default{
  name: 'login',
  data(){
    return {
      left: 'right',
      loginForm:{
        account: 'tester@yuejiadian.com',
        password: 'qwer1234'
      },
      token: '',
      msg: ''
    }
  },
  mounted(){
    this.$store.commit(types.LOGOUT)
  },
  methods: {
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if(valid){

          this.axios.post(api.login_path, {email: this.loginForm.account, password: this.loginForm.password}).then(response => {
            // 设置登录toke 并跳转到登录页面
            if(response.data.authentication_token){
              this.$store.commit(types.LOGIN, {'token': response.data.authentication_token, 'uid': response.data.uid})
              let redirect = decodeURIComponent(this.$route.query.redirect || '/');
              if(redirect == undefined || redirect == '/orders'){
                this.$router.push({
                  path: redirect
                })
              }
            }else{
              alert('--')
            }
          }).catch(function(err){
              alert(err.message)
          });
        }else{
          return false;
        }
      });
    },
    resetForm(formName){
      this.$refs[formName].resetFields();
    }
  }
}
</script>
